# coding: utf-8
from django.db import transaction
from django.http import HttpResponseRedirect, JsonResponse

from common.models.fun import Bottle, BottleGetTrace
from common.models.game import Game, GamePlayTrace


class LogicService(object):
    @classmethod
    def get_a_bottle_on_the_ocean(cls, user, want_type):
        """ 捞瓶子 """
        bottles_been_gotten_ids = BottleGetTrace.objects.all().values_list('bottle', flat=True)
        bottle_ids_which_been_gotten = Bottle.objects.filter(id__in=bottles_been_gotten_ids).values_list('id', flat=True)

        bottle = Bottle.objects.filter(sender__userprofile__sex=want_type).exclude(id__in=bottle_ids_which_been_gotten).exclude(sender=user).order_by('?').first()
        if bottle:
            assert user != bottle.sender
            BottleGetTrace.objects.create(getter=user, bottle=bottle)

        return bottle


    @classmethod
    def submit_game_score(cls, user_id, game_id, score):
        trace = GamePlayTrace.objects.filter(game_id=game_id, user_id=user_id).first()

        if trace:
            if score > trace.score:
                trace.score = score
                trace.save()
        else:
            GamePlayTrace.objects.create(game_id=game_id, user_id=user_id, score=score)

